package com.bytedance.douyinclouddemo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/*import com.aliyun.tea.TeaException;
import com.douyin.openapi.client.Client;
import com.douyin.openapi.client.models.WebcastmateInfoRequest;
import com.douyin.openapi.client.models.WebcastmateInfoResponse;
import com.douyin.openapi.credential.models.Config;
import com.aliyun.tea.TeaException;
import com.douyin.openapi.client.models.WebcastmateInfoRequest;
import com.douyin.openapi.client.models.WebcastmateInfoResponse;*/
import com.bytedance.douyinclouddemo.model.JsonResponse;
import com.bytedance.douyinclouddemo.model.LivePlayAPIResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DyLiveRoom {
    private static final String APPID = "tt53fb2546ccf282e610";
    private static final String SECRET = "ce8c9205d686d25e045aa65a40e459121454c48c";
    public static JSONObject  getLiveRoomInfo(String token) {
        try {
            token=UNicode2Str.convertUnicodeEscapeSequences(token);
            log.info("dyToken :{}",token);
            //token="OqXyZBSyFKdYr/CXCvslRwVEeVeOBM3in5VdsD2NK1maU/MBq5gujUr9hh7ieAq4R43pCskkYO4pyAEJJNwlL9ANBliBpAJsD+E5gSL4KVVWJnUvCCVNxQuD6MISqIrZYXWt2QfIiuxGCJky";
            //  token="COcn3oqTzBrKxumjn4kopFRakxsBFSwe7LFyq/kRCmdURTQxj+ylvlFcZV+6Zwf5BsT3R65c9DCOsEoBovR5jNgM7k3F5LJbesOIkFIzhNnJa/cQhiEu6oVzOHaPIcsORZ2A0nXDdVHw19Iv";
            String accessToken=createAccessToken();
            JSONObject rst = okHttpCallLiveRoom("https://webcast.bytedance.com/api/webcastmate/info", accessToken, token);

            System.out.println(rst.toString());
            return rst;

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    private static String createAccessToken() {
        JSONObject json = new JSONObject();
        json.put("appid", APPID);
        json.put("secret", SECRET);
        json.put("grant_type", "client_credential");
        String accessToken = okHttpCall("https://developer.toutiao.com/api/apps/v2/token", json.toJSONString());
        return accessToken;
    }
/*

    public static void getLiveRoomInfo2(String token) {
        try {
            Config config = new Config().setClientKey(APPID).setClientSecret(SECRET); // 改成自己的app_id跟secret
            Client client = new Client(config);
*/
/*             构建请求参数，该代码示例中只给出部分参数，请用户根据需要自行构建参数值
                token:
                   1.若用户自行维护token,将用户维护的token赋值给该参数即可
                   2.SDK包中有获取token的函数，请根据接口path在《OpenAPI SDK 总览》文档中查找获取token函数的名字
                     在使用过程中，请注意token互刷问题
                header:
                   sdk中默认填充content-type请求头，若不需要填充除content-type之外的请求头，删除该参数即可*//*


            WebcastmateInfoRequest sdkRequest = new WebcastmateInfoRequest();
            sdkRequest.setToken(token);
            String accessToken=createAccessToken();
            sdkRequest.setAccessToken(accessToken);
            //sdkRequest.setXToken("k23cd*****");
            WebcastmateInfoResponse sdkResponse = client.WebcastmateInfo(sdkRequest);
            Long roomId = sdkResponse.getData().getInfo().getRoomId();
            String anchorOpenId = sdkResponse.getData().getInfo().getAnchorOpenId();
            String avatarUrl = sdkResponse.getData().getInfo().getAvatarUrl();
            String nickName = sdkResponse.getData().getInfo().getNickName();
            System.out.println("直播间ID：" + roomId+"\n主播OpenId：" + anchorOpenId+"\n主播头像：" + avatarUrl+"\n主播昵称：" + nickName);

        } catch (TeaException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
*/

    public static String okHttpCall(String url, String body) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .post(
                        okhttp3.RequestBody.create(
                                MediaType.parse("application/json; charset=utf-8"),
                                body
                        )
                )
                .build();

        try {
            Response httpResponse = client.newCall(request).execute();
            if(httpResponse.isSuccessful()){
                String jsonstr = httpResponse.body().string();
                log.info("dyServer9010 http call done, response: {}", jsonstr);
                Object json = JSONObject.parse(jsonstr);
                JSONObject jsonObject = JSONObject.parseObject(jsonstr);
                log.info("dyServer9010 http call done, response: {}", JSON.toJSONString(httpResponse));
                if(jsonObject.getInteger("err_no")==0){
                    return jsonObject.getJSONObject("data").getString("access_token");
                }else {
                    return null;
                }
            }
        } catch (IOException e) {
            log.error("dyServer9010 http call exception, e: ", e);
        }
        return null;
    }


    public static JSONObject okHttpCallLiveRoom(String url, String accessToken,String dyToken) {
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder()
                .add("token", dyToken)   //"OqXyZBSyFKdYr/CXCvslRwVEeVeOBM3in5VdsD2NK1maU/MBq5gujUr9hh7ieAq4R43pCskkYO4pyAEJJNwlL9ANBliBpAJsD+E5gSL4KVVWJnUvCCVNxQuD6MISqIrZYXWt2QfIiuxGCJky")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .addHeader("x-token",accessToken)
                .post(formBody)
                .build();

        try {
            Response httpResponse = client.newCall(request).execute();
            if(httpResponse.isSuccessful()){
                String jsonstr = httpResponse.body().string();
                log.info("dyServer9010 http call done, response: {}", jsonstr);
                Object json = JSONObject.parse(jsonstr);
                JSONObject jsonObject = JSONObject.parseObject(jsonstr);
                log.info("dyServer9010 http call done, response: {}", JSON.toJSONString(httpResponse));
                if(jsonObject.getInteger("errcode")==0){
                    JSONObject liveRoomJson = jsonObject.getJSONObject("data").getJSONObject("info");
                    String anchorOpenId = liveRoomJson.getString("anchor_open_id");
                    String avatarUrl = liveRoomJson.getString("avatar_url");
                    String nickName = liveRoomJson.getString("nick_name");
                    String roomId = liveRoomJson.getString("room_id");
                    System.out.println("直播间ID：" + roomId+"\n主播OpenId：" + anchorOpenId+"\n主播头像：" + avatarUrl+"\n主播昵称：" + nickName);
                    callContainerExample(APPID,roomId,anchorOpenId,avatarUrl,nickName,accessToken);
                    return jsonObject.getJSONObject("data").getJSONObject("info");
                }else {
                    return jsonObject.getJSONObject("data");
                }
            }
        } catch (Exception e) {
            log.error("dyServer9010 http call exception, e: ", e);
        }
        return null;
    }


    public static boolean callContainerExample(String appID,String roomID,String anchorOpenID,String avatarUrl,String nickName,String accessToken) {
        // 开发者可以直接通过请求头获取直播间信息,无需自行通过token置换

//        // 应用id
//        String appID = httpRequest.getHeader("X-TT-AppID");
//        // 直播间id
//        String roomID = httpRequest.getHeader("X-Room-ID");
//        // 主播id
//        String anchorOpenID = httpRequest.getHeader("X-Anchor-OpenID");
//        // 主播头像url
//        String avatarUrl = httpRequest.getHeader("X-Avatar-Url");
//        // 主播昵称
//        String nickName = httpRequest.getHeader("X-Nick-Name");

        log.info("appID: {}, roomID: {}, anchorOpenID: {}, avatarUrl: {}, nickName: {}", appID,
                roomID, anchorOpenID, avatarUrl, nickName);


        // 调用弹幕玩法服务端API，开启直播间推送任务，开启后，开发者服务器会通过/live_data_callback接口 收到直播间玩法指令
        List<String> msgTypeList = new ArrayList<>();
        msgTypeList.add("live_like");
        msgTypeList.add("live_comment");
        msgTypeList.add("live_gift");
        msgTypeList.add("live_fansclub");

        for (String msgType : msgTypeList) {
            boolean result = startLiveDataTask(appID, roomID, msgType,accessToken);
            if (result) {
                log.info("{} 推送开启成功", msgType);
            } else {
                log.error("{} 推送开启失败", msgType);
            }
        }
        return true;
    }

    /**
     * startLiveDataTask: 开启推送任务：<a href="https://developer.open-douyin.com/docs/resource/zh-CN/interaction/develop/server/live/danmu#%E5%90%AF%E5%8A%A8%E4%BB%BB%E5%8A%A1">...</a>
     *
     * @param appID   小玩法appID
     * @param roomID  直播间ID
     * @param msgType 评论/点赞/礼物/粉丝团
     */
    private static boolean startLiveDataTask(String appID, String roomID, String msgType,String accessToken) {
        // example: 通过java OkHttp库发起http请求,开发者可使用其余http访问形式
        OkHttpClient client = new OkHttpClient();
        String body = new JSONObject()
                .fluentPut("roomid", roomID)
                .fluentPut("appid", appID)
                .fluentPut("msg_type", msgType)
                .toString();
        Request request = new Request.Builder()
                .url("http://webcast.bytedance.com/api/live_data/task/start") // 内网专线访问小玩法openAPI,无需https协议
                .addHeader("Content-Type", "application/json") // 无需维护access_token
                .addHeader("access-token", accessToken)
                .post(
                        okhttp3.RequestBody.create(
                                MediaType.get("application/json; charset=utf-8"),
                                body
                        )
                )
                .build();

        try {
            Response httpResponse = client.newCall(request).execute();
            if (httpResponse.code() != 200) {
                log.error("开启推送任务失败,http访问非200");
                return false;
            }
            LivePlayAPIResponse livePlayAPIResponse
                    = JSON.parseObject(httpResponse.body().string(), LivePlayAPIResponse.class);
            if (livePlayAPIResponse.getErrNo() != 0) {
                log.error("开启推送任务失败，错误信息: {}", livePlayAPIResponse.getErrorMsg());
                return false;
            }
        } catch (IOException e) {
            log.error("开启推送任务异常,e: {}", e.getMessage(), e);
            return false;
        }
        return true;
    }
}
